package com.sskj.gcc.ui.activity;


import android.Manifest;
import android.net.http.SslError;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.AgentWebUIControllerImplBase;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.sskj.common.widget.DensityWebView;
import com.sskj.gcc.R;
import com.sskj.gcc.bean.GuideListBean;
import com.sskj.gcc.presenter.GuideWebActivityPresenter;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zzhoujay.richtext.RichText;

import butterknife.BindView;

@Route(path = RConfig.APP_GUIDE_WEB)
public class GuideWebActivity extends BaseActivity<GuideWebActivityPresenter> {
    @BindView(R.id.webView)
    DensityWebView webView;

    @BindView(R.id.content_tv)
    TextView content_tv;
    @Autowired
    String content;
    @Autowired
    String time;
    @Autowired
    String title;
    @Autowired
    String id;
    private AgentWeb mAgentWeb;
    @Autowired
    String url = "";
    @Autowired
    String head;
    @Autowired
    boolean isService;


    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_guide_web;
    }

    @Override
    public GuideWebActivityPresenter getPresenter() {
        return new GuideWebActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        AgentWebConfig.DEBUG=true;
        setTitle(head);
        if (!TextUtils.isEmpty(url)) {
            if (!url.contains("http")) {
                url = "http://" + url;
            }
        }
        initWeb();
        if (isService){
            content_tv.setVisibility(View.GONE);
        }else {
            content_tv.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(url)) {
            if (!isService){
                updateUI();
            }
        }
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(content)) {
            mPresenter.getContent(id);
        }
    }

    public void updateUI() {
        if (TextUtils.isEmpty(content)) {
            return;
        }

        RichText.fromHtml(content).into(content_tv);

//        String CSS_STYLE = "<style>* {font-size:40px;line-height:60px;} p {color:#fff;} a {color:#fff;} img {width:100%;} pre {font-size:40pt;line-height:60pt;font-family:Courier New,Arial;border:1px solid #ddd;border-left:5px solid #fff;background:#fff;padding:5px;}</style>";
//
//        content = content.replaceAll("<span.*?</span><span.*?</span>", "").replace("“", "").replace("”", "");
//        content = "<font style=\"color:#ffffff;font-size:15px;line-height:80px;\">" + title + "</font><br>\n" +
//                "<div style=\"font-size:12px;text-align:left;margin-top:18px;color:#ffffff\">" + time + "</div><br>"
//                + "<hr size='0.1px',style=\"margin-top:18px;background-color:#29455E\"></hr>"
//                + "<div  style=\"font-size:12px;margin-top:14px;color:#1C1F22\">" + content + "</div" +
//                ">";
//        content = "<body style=\"background:#29455E;margin:0;padding-left:15px;padding-right:15px;margin-top:20px\">" + content + "</body" +
//                ">";
//        mAgentWeb.getUrlLoader().loadDataWithBaseURL(HttpConfig.BASE_URL, CSS_STYLE + content, "text/html; charset=UTF-8", null, HttpConfig.BASE_URL);

    }

    public void initWeb() {
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(agree -> {
                    if (agree) {
                        mAgentWeb = AgentWeb.with(this)//这里需要把 Activity 、 和 Fragment  同时传入
                                .setAgentWebParent(webView, new LinearLayout.LayoutParams(-1, -1))
                                .useDefaultIndicator()
                                .setAgentWebUIController(new WebUIController())
                                .setWebViewClient(new WebViewClient(){
                                    @Override
                                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                                        handler.proceed();
                                    }
                                })
                                .setWebChromeClient(new WebChromeClient(){
                                    @Override
                                    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                                        return super.onJsAlert(view, url, message, result);
                                    }
                                })
                                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //注意这里开启 strict 模式 ， 设备低于 4.2 情况下回把注入的 Js 全部清空掉 ， 这里推荐使用 onJsPrompt 通信
                                .createAgentWeb()
                                .ready()
                                .go(url);
                    }
                });


    }




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return true;
    }

    @Override
    protected void onPause() {
        if (mAgentWeb!=null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();

    }

    @Override
    protected void onResume() {
        if (mAgentWeb!=null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAgentWeb!=null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
    }

    public void getContentSuccess(GuideListBean data) {
        content = data.getContent();
        updateUI();
    }
}
